const axios = require('axios');
const cheerio = require('cheerio');
const cloud = require('wx-server-sdk');

// 初始化云开发环境
cloud.init({
  env: 'lvtengweishi-4gvg0d2h59537d91',
  throwOnCode: false
});

// 配置信息 - 针对不同网站的解析规则
const WEBSITES = {
  "新疆维吾尔自治区农业农村厅_农业农村动态": {
    contentSelector: "div.detail-content p.p"
  },
  "新疆维吾尔自治区农业农村厅_业务工作": {
    contentSelector: "div.detail-content p.p"
  },
  "中国农业农村信息网_农业新闻": {
    contentSelector: "div.TRS_Editor p"
  },
  "中国农业农村信息网_全国信息联播": {
    contentSelector: "div.TRS_Editor p" 
  },
  "中国农业农村信息网_通知公告": {
    contentSelector: "div.content_body_box.ArticleDetails p:not(:has(a[href]))" 
  },
  "中国农业农村信息网_最新发布": {
    contentSelector: "div.TRS_Editor p" 
  },
  "云南省农业农村厅_云农快讯": {
    contentSelector: "div.format.yh p" 
  },
  "四川省农业农村厅_市县联播": {
    contentSelector: "div.content UCAPCONTENT p" 
  },
  "山东省农业农村厅_通知公告": {
    contentSelector: "div.trs_editor_view.TRS_UEDITOR p" 
  }
};

// 请求头
const headers = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
};

// 解析网页内容的函数
async function parseUrlContent(url, siteName) {
  try {
    console.log(`开始解析网址: ${url}，网站配置: ${siteName}`);
    
    // 根据网站名称获取对应的解析规则
    const config = WEBSITES[siteName];
    
    if (!config) {
      return {
        success: false,
        url: url,
        message: `未找到网站 "${siteName}" 的解析配置`
      };
    }

    // 发送请求获取网页内容
    const response = await axios.get(url, { headers });
    const $ = cheerio.load(response.data);
    
    // 提取内容
    const contentList = [];
    $(config.contentSelector).each((i, el) => {
      const text = $(el).text().trim();
      if (text) {
        contentList.push(text);
      }
    });
    const content = contentList.join('\n\n');  // 段落间用两个换行分隔
    
    return {
      success: true,
      url: url,
      content: content || "未找到有效内容"
    };
  } catch (error) {
    console.error(`解析网址失败: ${error.message}`);
    return {
      success: false,
      url: url,
      message: `解析失败: ${error.message}`
    };
  }
}

// 云函数入口
exports.main = async (event, context) => {
  try {
    // 从事件参数中获取网址和网站名称
    const url = event.url;
    const siteName = event.siteName;
    
    if (!url) {
      return { code: 1, message: "请提供要解析的网址", data: null };
    }
    
    if (!siteName) {
      return { code: 1, message: "请提供网站名称以匹配解析规则", data: null };
    }
    
    console.log(`收到解析请求，网址: ${url}，网站名称: ${siteName}`);
    
    // 解析网址内容
    const result = await parseUrlContent(url, siteName);
    
    return {
      code: result.success ? 0 : -1,
      message: result.success ? "解析成功" : result.message,
      data: {
        url: result.url,
        content: result.content
      }
    };
  } catch (error) {
    console.error('全局错误:', error.message);
    return { code: -1, message: error.message, data: null };
  }
};